﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using DataAccess;
using com.chttl.ienc.bean;
using java.util;
using System.Data;
using System.Data.SqlClient;

namespace iEN.Organization
{
    public partial class GroupManage : System.Web.UI.Page
    {      
        #region protected void Page_Load(object sender, EventArgs e) //初始頁面, 判斷權限
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)//先判斷是否已經登入過
            {
                if (Session["LoginName"] == null)
                {
                    Response.Write("<script>alert('請先登入！！');location.href='../Login.aspx';</script>");
                }

                initUI();


                if (Session["SysAdmin"].ToString() != "2")
                {
                    lblMsg.Visible = true;
                    //Panel0.Visible = false;
                    Panel2.Visible = false;
                    Panel3.Visible = false;
                    tvMeterGrp.Visible = false;
                }
            }
        }
        #endregion

        private void initUI()
        {
            tbGrpName.Text = "";
            tbGrpCategory.Text = "";
            tbGrpDescription.Text = "";

            TextBox1.Text = "";
            ddGrpCategory.ClearSelection();
            TextBox3.Text = "";

            try
            {
                //建立組織群組樹狀圖
                genMeterGroupTree();
            }
            catch
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤，無法建立組織群組樹狀圖！')", true);
                return;
            }
        }

        private void recGenTree(DataTable dt, ref TreeNode parentNode)
        {

            string parentId = parentNode.Value == "-1" ? "0" : parentNode.Value;
            dt.DefaultView.RowFilter = "_parent_id = " + parentId;
            DataTable dtBuffer = dt.DefaultView.ToTable();

            TreeNode nodeBuffer;

            for (int i = 0; i < dtBuffer.Rows.Count; i++)
            {
                nodeBuffer = new TreeNode();
                nodeBuffer.SelectAction = TreeNodeSelectAction.Select;
                nodeBuffer.Text = dtBuffer.Rows[i]["_name"].ToString();
                nodeBuffer.Value = dtBuffer.Rows[i]["_id"].ToString();
                parentNode.ChildNodes.Add(nodeBuffer);

                recGenTree(dt, ref nodeBuffer);
            }
        }

        private void genMeterGroupTree()
        {
            // clear all
            tvMeterGrp.Nodes.Clear();

            // add the root
            TreeNode root = new TreeNode();
            root.SelectAction = TreeNodeSelectAction.Select;  //群組層級
            root.Text = "成大宿舍iEN";  //設定節點的顯示文字
            root.Value = "-1";  //設定節點的數值

            DataTable dtOrgGroup = new DBAccess().getOrgGroupTable("1");  //取得ALLOrgGroup
            if (dtOrgGroup == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤！')", true);
                return;
            }

            recGenTree(dtOrgGroup, ref root);

            tvMeterGrp.Nodes.Add(root);
            tvMeterGrp.ExpandAll();
        }

        /*
        #region private void CreateMeterGroupTree() //建立樹狀節點
        private void CreateMeterGroupTree()
        {

            //先清空原來的Tree node
            tvMeterGrp.Nodes.Clear();

            //加入根節點
            TreeNode RootNode = new TreeNode();
            RootNode.SelectAction = TreeNodeSelectAction.Select;  //群組層級
            RootNode.Text = "成大宿舍iEN";  //設定節點的顯示文字
            RootNode.Value = "-1";  //設定節點的數值

            DataTable dtOrgGroup = new DBAccess().getOrgGroupTable("1");  //取得ALLOrgGroup
            if (dtOrgGroup == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('資料庫抓取資料有誤！')", true);
                return;
            }

            DataTable dtMeter = dtOrgGroup.Copy();
            DataTable dtBuilding = dtOrgGroup.Copy();
            DataTable dtTemp = dtOrgGroup.Copy();
            DataTable dtFloor, dtBlock;
            dtBuilding.DefaultView.RowFilter = "_level=1";
            dtBuilding = dtBuilding.DefaultView.ToTable();

            for (int i = 0; i < dtBuilding.Rows.Count; i++)
            {
                TreeNode tnNode1 = new TreeNode();
                tnNode1.SelectAction = TreeNodeSelectAction.Select;  //群組層級
                tnNode1.Text = dtBuilding.Rows[i]["_name"].ToString();  //設定節點的顯示文字
                tnNode1.Value = dtBuilding.Rows[i]["_id"].ToString(); ;  //設定節點的數值
                RootNode.ChildNodes.Add(tnNode1);
                dtMeter.DefaultView.RowFilter = "_parent_id=" + dtBuilding.Rows[i]["_id"].ToString();
                dtFloor = dtMeter.DefaultView.ToTable();
                if (dtFloor != null)
                {
                    for (int j = 0; j < dtFloor.Rows.Count; j++)
                    {
                        TreeNode tnNode2 = new TreeNode();
                        tnNode2.SelectAction = TreeNodeSelectAction.Select;  //群組層級
                        tnNode2.Text = dtFloor.Rows[j]["_name"].ToString();  //設定節點的顯示文字
                        tnNode2.Value = dtFloor.Rows[j]["_id"].ToString(); ;  //設定節點的數值
                        tnNode1.ChildNodes.Add(tnNode2);
                        dtTemp.DefaultView.RowFilter = "_parent_id=" + dtFloor.Rows[j]["_id"].ToString();
                        dtBlock = dtTemp.DefaultView.ToTable();
                        if (dtBlock != null)
                        {
                            for (int k = 0; k < dtBlock.Rows.Count; k++)
                            {
                                TreeNode tnNode3 = new TreeNode();
                                tnNode3.SelectAction = TreeNodeSelectAction.Select;  //群組層級
                                tnNode3.Text = dtBlock.Rows[k]["_name"].ToString();  //設定節點的顯示文字
                                tnNode3.Value = dtBlock.Rows[k]["_id"].ToString(); ;  //設定節點的數值
                                tnNode2.ChildNodes.Add(tnNode3);
                            }
                        }
                    }
                }
            }
            tvMeterGrp.Nodes.Add(RootNode);
            tvMeterGrp.ExpandAll();
            //tvMeterGrp.CollapseAll();
        }
        #endregion
         */

        #region protected void tvMeterGrp_SelectedNodeChanged(object sender, EventArgs e) //點選組織群組顯示組織詳細資料
        protected void tvMeterGrp_SelectedNodeChanged(object sender, EventArgs e)
        {

            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有瀏覽此頁面的權限！')", true);
                return;
            }
            
            string strMeterValue = tvMeterGrp.SelectedNode.Value;
            if (strMeterValue == "-1")
            {
                tbGrpName.Text = tvMeterGrp.SelectedNode.Text;
                tbGrpCategory.Text = "CUSTOMER";
                tbGrpDescription.Text = "iEN";

                ddGrpCategory.SelectedIndex = 1;
            }
            else
            {
                DataTable dtController = new DBAccess().getOrgGroupTable("1");  //取得ALLOrgGroup
                dtController.DefaultView.RowFilter = "_id =" + strMeterValue;
                dtController = dtController.DefaultView.ToTable();
                if (dtController != null)
                {
                    tbGrpName.Text = dtController.Rows[0]["_name"].ToString();
                    tbGrpCategory.Text = dtController.Rows[0]["_type"].ToString();
                    tbGrpDescription.Text = dtController.Rows[0]["_desc"].ToString();
                }

                int ddlIndex = int.Parse(dtController.Rows[0]["_level"].ToString());

                if (ddlIndex != 3)
                    ddlIndex++;
                else
                    ddlIndex = 0;

                ddGrpCategory.SelectedIndex = ddlIndex;
            }
        }
        #endregion

        private string getOrgPath(DataTable dt, string current_id)
        {

            DataTable dtCurrent = dt.Copy();
            dtCurrent.DefaultView.RowFilter = "_id = " + current_id;
            dtCurrent = dtCurrent.DefaultView.ToTable();
            string currentRefID = dtCurrent.Rows[0]["_ref_id"].ToString();
            string parentID = dtCurrent.Rows[0]["_parent_id"].ToString();

            if (parentID != "0")
                return getOrgPath(dt, parentID) + "/" + currentRefID;
            else
                return "/1/" + currentRefID;
        }

        private string genUniqueRefID(DataTable dt)
        {
            string result = "";
            bool checkFlag = true;
            char[] key = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
                                      'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
                                      'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
                                      'u', 'v', 'w', 'x', 'y', 'z' };
            DataTable dtBuffer;

            System.Random rndGen = new System.Random();

            while (checkFlag == true)
            {
                result = "";

                for (int i = 0; i < 32; i++)
                {
                    int rnd = rndGen.Next(0, 36);
                    result += key[rnd];
                }

                dt.DefaultView.RowFilter = "_ref_id = '" + result + "'";
                dtBuffer = dt.DefaultView.ToTable();

                if (dtBuffer.Rows.Count == 0)
                    checkFlag = false;
            }

            return result;
        }

        #region protected void btAddNewGrp_Click(object sender, EventArgs e) //新增組織群組名稱資訊按鈕
        protected void btAddNewGrp_Click(object sender, EventArgs e)
        {
            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有瀏覽此頁面的權限！')", true);
                return;
            }
            
            if (tvMeterGrp.SelectedNode == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('請先選擇欲新增之組織群組節點！')", true);
                return;
            }

            if (TextBox1.Text.Trim() == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('名稱不可為空白！')", true);
                return;
            }

            string path;
            DataTable dtOrg = new DBAccess().getOrgGroupTable("1");  //取得ALLOrgGroup
            dtOrg.DefaultView.RowFilter = "_id = " + tvMeterGrp.SelectedNode.Value;
            DataTable dtBuffer = dtOrg.DefaultView.ToTable();

            if (tvMeterGrp.SelectedNode.Value != "-1" && dtBuffer.Rows[0]["_level"].ToString() == "3")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('無法在此組織群組節點下新增！')", true);
                return;
            }

            // user select root "iEN"
            //if (tvMeterGrp.SelectedNode.Value == "-1")
            //    path = "/1";
            //else
            //    path = getOrgPath(dtOrg, tvMeterGrp.SelectedNode.Value);

            string refID = genUniqueRefID(dtOrg);
            string type = ddGrpCategory.SelectedItem.Text;

            bool blnRet = new DBAccess().addOrgGroup(tvMeterGrp.SelectedNode.Value, TextBox1.Text, TextBox3.Text, refID);

            //OrgGroup org = new WebService().createOrgGroup6(path, refID, TextBox1.Text, "LOCATION", type, TextBox3.Text);

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "群組名稱：" + TextBox1.Text;

            if (blnRet == true)
            {
                new DBAccess().addEventLog(strAccount, strIP, 21, strMemo, "0", int.Parse(tvMeterGrp.SelectedNode.Value));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增成功！')", true);
            }
            else
            {
                new DBAccess().addEventLog(strAccount, strIP, 21, strMemo, "1", int.Parse(tvMeterGrp.SelectedNode.Value));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('新增失敗！')", true);
            }

            initUI();
        }
        #endregion

        #region private btModGrp_Click(object sender, EventArgs e) //修改組織群組節點
        protected void btModGrp_Click(object sender, EventArgs e)
        {
            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有瀏覽此頁面的權限！')", true);
                return;
            }
            
            if (tvMeterGrp.SelectedNode == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('請先選擇欲修改之組織群組節點！')", true);
                return;
            }

            if (tvMeterGrp.SelectedNode.Value == "-1")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('組織群組之節點無法修改暨刪除！')", true);
                return;
            }

            if (tbGrpName.Text.Trim() == "")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('名稱不可為空白！')", true);
                return;
            }

            //DataTable dtOrgG = new DBAccess().getOrgGroupTable("1");  //取得ALLOrgGroup

            //string currentPath = getOrgPath(dtOrgG, tvMeterGrp.SelectedNode.Value);

            //OrgGroup orgGroup = new WebService().getOrgGroupByPath1(currentPath);

            //orgGroup.setName(tbGrpName.Text);
            //orgGroup.setType(tbGrpCategory.Text);
            //orgGroup.setDescription(tbGrpDescription.Text);

            //new WebService().modifyOrgGroup1(orgGroup);

            bool blnRet = new DBAccess().updateOrgGroup(tvMeterGrp.SelectedNode.Value, tbGrpName.Text, tbGrpDescription.Text);

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "ID：" + tvMeterGrp.SelectedNode.Value + "//名稱：" + tbGrpName.Text;

            if (blnRet == true)
            {
                new DBAccess().addEventLog(strAccount, strIP, 23, strMemo, "0", int.Parse(tvMeterGrp.SelectedNode.Value));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改成功！')", true);
            }
            else
            {
                new DBAccess().addEventLog(strAccount, strIP, 23, strMemo, "1", int.Parse(tvMeterGrp.SelectedNode.Value));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('修改失敗！')", true);
            }

            initUI();
        }
        #endregion

        #region private void btDelGrp_Click(object sender, EventArgs e) //刪除組織群組節點
        protected void btDelGrp_Click(object sender, EventArgs e)
        {
            if (Session["SysAdmin"].ToString() != "2")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('你沒有瀏覽此頁面的權限！')", true);
                return;
            }
            
            if (tvMeterGrp.SelectedNode == null)
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('請先選擇欲刪除之組織群組節點！')", true);
                return;
            }

            if (tvMeterGrp.SelectedNode.Value == "-1")
            {
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('組織群組之節點無法修改暨刪除！')", true);
                return;
            }

            //string strMeterValue = tvMeterGrp.SelectedNode.Value;

            //DataTable dt = new DBAccess().getOrgGroupTable("1");
            //string path = getOrgPath(dt, strMeterValue);

            //bool result = new WebService().removeOrgGroup1(path);

            bool blnRet = new DBAccess().deleteOrgGroup(tvMeterGrp.SelectedNode.Value);

            string strAccount = Session["LoginAccount"].ToString();
            string strIP = Session["LoginIP"].ToString();
            string strMemo = "ID：" + tvMeterGrp.SelectedNode.Value + "//名稱：" + tbGrpName.Text;

            if (blnRet == true)
            {
                new DBAccess().addEventLog(strAccount, strIP, 22, strMemo, "0", int.Parse(tvMeterGrp.SelectedNode.Value));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('刪除成功！')", true);
            }
            else
            {
                new DBAccess().addEventLog(strAccount, strIP, 22, strMemo, "1", int.Parse(tvMeterGrp.SelectedNode.Value));
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", "alert('刪除失敗，請確認該節點下無其他節點！')", true);
            }
            initUI();
        }
        #endregion
    }
}